from django.http import HttpResponse
from django.shortcuts import redirect, render
from MyBlog import models

# data = []
# i = 0
# while i < 10:
#     article = {}
#     article['title']='文章'+str(i)
#     article['content']='内容'+str(i)
#     article['id'] = str(i)
#     data.append(article)
#     i += 1
    
def list(request):
    context = {}
    context['list'] = models.Article.objects.all()
    return render(request, 'list.html', context)


def show(request,id):
    model = models.Article.objects.get(id=id)
    return render(request,'show.html',{'model':model})

# def list(request):
#     context = {}
#     context['list'] = data
#     return render(request, 'list.html', context)

# def show(request,id):
#     model = {}
#     for m in data:
#         if m['id'] == id:
#             model = m
#             break
#     return render(request,'show.html',model)

def add(request):
    return render(request, 'add.html')

def addPost(request):
    # article = {}
 
    # article['title'] = request.POST['title']
    # article['content']=request.POST['content']
    # index = len(data)
    # if index == 0:
    #     article['id']= '1'
    # else:
    #     article['id'] = str(int(data[index - 1]['id']) + 1)

    # data.append(article)
    # return redirect('/list/')

    #1.构造数据库orm的对象，赋值
    m = models.Article()
    m.content = request.POST['content']
    m.title = request.POST['title']

    #2. 入库
    m.save()

    #3.给用户提示及相关跳转
    return redirect('/list/')




def delete(request,id):
    # for m in data:
    #     if m['id'] == id:
    #         data.remove(m)  #数组的remove方法表示从数组里删除元素
    #         break

    # 1.找到数据
    m = models.Article.objects.get(id=id)
    # m = models.Article.objects.filter(id=id).first()
    # 2.执行删除
    m.delete()

    return redirect('/list/')

def edit(request, id):
    model = models.Article.objects.get(id=id)
    # model = {}
    # for m in data:
    #     if m['id'] == id:
    #         model = m
    #         break
    return render(request,'edit.html', {'model':model})


def editPost(request, id):
    # for m in data:
    #     if m['id'] == id:
    #         m['title'] = request.POST['title']
    #         m['content']=request.POST['content']
    #         break
    # 1.找到数据
    model = models.Article.objects.get(id=id)
    # 2.修改
    model.title = request.POST['title']
    model.content = request.POST['content']
    # 3.入库
    model.save()
    return redirect('/list/')
    